package handler

import (
	"context"
	"fmt"
	"github.com/jinzhu/gorm"
	"rpcSrv/dbs/mysqlGORM"
	"rpcSrv/entitys"
	pb "rpcSrv/proto/like"
	"rpcSrv/utils"
	"time"
)

type LikeHdl struct {
}

func (this *LikeHdl) DoLike(ctx context.Context, req *pb.LikeReqParams) (resp *pb.LikeRespParams, err error) {
	db, err := mysqlGORM.GetMysqlDB()
	if utils.CheckErr(err) {
		return nil, err
	}
	n := 0
	likeData := new(entitys.Like)
	if notFound := db.Table(new(entitys.Like).TableName()).
		Where("uid = ?", req.GetUid()).
		Where("tb_name = ?", req.GetTableName()).
		Where("target_id = ?", req.GetTargetId()).
		Limit(1).Scan(likeData).RecordNotFound(); !notFound {
		n = 1
	}
	tx := db.Begin()
	if n == 1 {
		if err = tx.Table(req.GetTableName()).Where("id = ?", likeData.TargetId).UpdateColumn("like_number", gorm.Expr("like_number - ?", 1)).Error; utils.CheckErr(err) {
			tx.Rollback()
			return nil, err
		}
		sql := fmt.Sprintf("delete from %v where id = %v;", new(entitys.Like).TableName(), likeData.ID)
		if err = tx.Exec(sql).Error; utils.CheckErr(err) {
			tx.Rollback()
			return nil, err
		}
	} else {
		likeData.TargetId = int(req.GetTargetId())
		likeData.Uid = int(req.GetUid())
		likeData.TbName = req.GetTableName()
		likeData.CreatedTimestamp = time.Now().Unix()
		if err = tx.Table(req.GetTableName()).Where("id = ?", likeData.TargetId).UpdateColumn("like_number", gorm.Expr("like_number + ?", 1)).Error; utils.CheckErr(err) {
			tx.Rollback()
			return nil, err
		}
		if err = tx.Table(likeData.TableName()).Create(likeData).Error; utils.CheckErr(err) {
			tx.Rollback()
			return nil, err
		}
	}
	tx.Commit()
	return &pb.LikeRespParams{Flag: int64(n)}, nil
}

func (this *LikeHdl) IsLike(ctx context.Context, req *pb.LikeReqParams) (resp *pb.LikeRespParams, err error) {
	db, err := mysqlGORM.GetMysqlDB()
	if utils.CheckErr(err) {
		return nil, err
	}
	n := 0
	if err = db.Table(new(entitys.Like).TableName()).
		Where("uid = ?", req.GetUid()).
		Where("tb_name = ?", req.GetTableName()).
		Where("target_id = ?", req.GetTargetId()).
		Count(&n).Error; utils.CheckErr(err) {
		return nil, err
	}
	if n > 0 {
		n = 1
	}
	return &pb.LikeRespParams{Flag: int64(n)}, nil
}
